import { inject, Ref } from "vue";
import { TableColumn, TableOptions, TableData, Pagination } from "../interface";
import { SearchOptions } from "../components/Tools/interface";
import { deepClone } from "@table/utils";

export const useData = () => {
  let tableData = inject<Ref<TableData>>("tableData");
  let originalTableColumns = inject<Ref<TableColumn[]>>("originalTableColumns") as Ref<TableColumn[]>;
  let options = inject<Ref<TableOptions>>("options") as Ref<TableOptions>;
  let tableColumns = inject<Ref<TableColumn[]>>("tableColumns") as Ref<TableColumn[]>;
  let searchOptions = inject<Ref<SearchOptions>>("searchOptions") as Ref<SearchOptions>;
  let doms = inject<Record<string, HTMLElement[]>>("doms") as Record<string, HTMLElement[]>;
  let api = inject<Function>("api");
  let pagination = inject<Pagination>("pagination");
  let tableScrollRef = inject("tableScrollRef");
  let afterApiTransformData = inject<Function>("afterApiTransformData");
  const eventBus = inject<any>("eventBus");
  const copyTableColumns = (): TableColumn[] => {
    return deepClone(tableColumns.value);
  };
  const copyOriginalTableColumns = (): TableColumn[] => {
    return deepClone(originalTableColumns.value);
  };

  const copySearchOptions = (): SearchOptions => {
    return deepClone(searchOptions.value);
  };

  const fn2string = (value: any) => {
    if (typeof value === "function") {
      return value.toString();
    }
    return value;
  };
  const string2fn = (value: any) => {
    if (typeof value === "string") {
      return new Function("return " + value)();
    }
    return value;
  };

  const transformColumnsString = (columns: TableColumn[]) => {
    columns = deepClone(columns);
    columns.forEach((item: any) => {
      item.filter && (item.filter.operator = fn2string(item.filter.operator));
      item.filter && (item.filter.value = fn2string(item.filter.value));
    });
    return columns;
  };

  // 初始化tableColumns
  const initTableColumns = () => {
    const setting = options.value?.setting as any;
    if (setting.show && setting.storage) {
      let value = (tableColumns.value = JSON.parse(localStorage.getItem(setting.storageKey) || "[]"));
      value.forEach((item: any) => {
        item.filter && (item.filter.operator = string2fn(item.filter.operator));
        item.filter && (item.filter.value = string2fn(item.filter.value));
      });
      if (value.length > 0) {
        // 赋值 isHidden 和 isFixed 、width、顺序取决于用户 其余重新赋值原始值并重新保存
        // 移除的字段需要在本地移除  新增不用管后期自己设置添加
        value = value.filter((item: any) => {
          return originalTableColumns.value.find(i => i.key === item.key);
        });
        value = value.map((item: TableColumn) => {
          const original = originalTableColumns.value.find(i => i.key === item.key);
          return {
            ...original,
            isHidden: item.isHidden,
            isFixed: item.isFixed
          };
        });
        tableColumns.value = value;
      } else {
        tableColumns.value = originalTableColumns.value.filter(item => !item.isHidden);
      }

      localStorage.setItem(setting.storageKey, JSON.stringify(transformColumnsString(tableColumns.value)));
    } else {
      tableColumns.value = originalTableColumns.value.filter(item => !item.isHidden);
    }
  };

  // 清除Table缓存
  const clearTableColumns = () => {
    const setting = options.value.setting as any;
    if (setting.show && setting.storage) {
      localStorage.removeItem(setting.storageKey as string);
      tableColumns.value = originalTableColumns.value.filter(item => !item.isHidden);
      localStorage.setItem(setting.storageKey, JSON.stringify(transformColumnsString(tableColumns.value)));
    }
  };
  // save tableColumns
  const saveTableColumns = () => {
    const setting = options.value.setting as any;
    if (setting.show && setting.storage) {
      tableColumns.value.forEach(item => {
        item.isMoreActive = false;
      });
      localStorage.setItem(setting.storageKey as string, JSON.stringify(transformColumnsString(tableColumns.value)));
    }
  };

  // 当前页面置为1

  const setCurrentPagination = () => {
    if (pagination) pagination.value.currentPage = 1;
  };

  return {
    originalTableColumns,
    tableColumns,
    copyTableColumns,
    copyOriginalTableColumns,
    searchOptions,
    copySearchOptions,
    options,
    initTableColumns,
    saveTableColumns,
    tableData,
    doms,
    tableScrollRef,
    clearTableColumns,
    api,
    afterApiTransformData,
    pagination,
    eventBus,
    setCurrentPagination
  };
};
